<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { addGrowthArchive, getStudentOptionInfoList } from '@/services/studentInfo'
import { useMemberStore } from '@/stores'
import type { StudentOptionItem } from '@/types/studentInfo'
// 获取会员Store实例
const memberStore = useMemberStore()

// 表单数据
const formData = ref({
  classTime: new Date().toISOString().split('T')[0] + ' ' + new Date().toTimeString().slice(0, 8),
  comment: '',
  score: 5,
  subjectId: null,
  subject: '',
  studentId: null,
  studentName: '',
  activityScore: 5,
  participationScore: 5,
  images: [] as string[],
})

const selectImageList = ref<string[]>([])
const studyStatus = ref(4)
const scheduleId = ref(1)
const loadingStudents = ref(false)

// 新增文件选择处理
const onFileSelect = (e: any) => {
  // 获取选择的图片临时文件路径
  const tempFilePaths = e.tempFilePaths || e.detail?.tempFilePaths
  if (!tempFilePaths) {
    console.error('未获取到图片路径:', e)
    return
  }

  // 计算添加后的总数
  const totalCount = selectImageList.value.length + tempFilePaths.length

  // 如果超过9张，给出提示
  if (totalCount > 9) {
    uni.showToast({ title: '最多只能上传9张图片', icon: 'none' })
  }

  // 更新图片数组，确保不超过9张
  const newImages = [...selectImageList.value, ...tempFilePaths].slice(0, 9)
  selectImageList.value = newImages
}

// 新增文件删除处理
const onFileDelete = (e: any) => {
  // 确保正确获取索引
  const index = e.index
  if (typeof index !== 'number') {
    console.error('无法获取删除索引:', e)
    return
  }
  selectImageList.value.splice(index, 1)
}

// 实现提交方法
const submitRecord = async () => {
  // 先处理图片上传
  let imageUrls: string[] = []
  if (selectImageList.value.length > 0) {
    // 上传图片
    for (const filePath of selectImageList.value) {
      const uploadResult = await uploadImage(filePath)
      if (uploadResult) {
        imageUrls.push(uploadResult)
      }
    }
  }

  const res = await addGrowthArchive({
    studentId: formData.value.studentId,
    subjectId: formData.value.subjectId,
    student: formData.value.studentName,
    subject: formData.value.subject,
    studyStatus: studyStatus.value,
    scheduleId: scheduleId.value,
    studyTime: formData.value.classTime,
    studyRecord: formData.value.comment,
    score: formData.value.score,
    activityScore: formData.value.activityScore,
    participationScore: formData.value.participationScore,
    attachment: imageUrls.join(';'),
  })
  if (res.code == 200) {
    uni.showToast({ title: '点评成功', icon: 'success' })
    // 返回上一页
    uni.navigateBack({
      success: () => {
        // 刷新上一页数据
        uni.$emit('refreshData')
      },
    })
  } else {
    uni.showToast({ title: res.msg || '点评失败', icon: 'error' })
  }
}

// 新增图片上传函数
const uploadImage = (filePath: string): Promise<string | null> => {
  return new Promise((resolve) => {
    // 获取token
    const token = memberStore.profile?.token || ''

    uni.uploadFile({
      url: '/wechat/student/uploadAttachment',
      filePath: filePath,
      name: 'file',
      header: {
        'content-type': 'multipart/form-data',
        Authorization: `Bearer ${token}`,
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const data = JSON.parse(res.data)
          resolve(data.url)
        } else {
          resolve(null)
        }
      },
      fail: () => {
        resolve(null)
      },
    })
  })
}
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

const back = () => {
  // 返回上一页
  uni.navigateBack({
    success: () => {
      // 刷新上一页数据
      uni.$emit('refreshData')
    },
  })
}

// 示例数据结构
const studentInfoList = ref<StudentOptionItem[]>([])

const getStudentInfoDataList = async () => {
  const res = await getStudentOptionInfoList({})
  studentInfoList.value = [...studentInfoList.value, ...res.data]
}

// 在script部分添加
const onPickerChange = (e: any) => {
  // 获取完整的选择路径
  const selectedItems = e.detail.value
  if (selectedItems && selectedItems.length >= 3) {
    // 第三级选项的值
    formData.value.studentId = selectedItems[2].value.split('-')[1]
    // 第三级选项的文本
    formData.value.studentName = selectedItems[2].text
    formData.value.subjectId = selectedItems[0].value.split('-')[1]
    formData.value.subject = selectedItems[0].text
    // 可以记录完整路径信息
    console.log('选择路径:', selectedItems)
  }
}
// 加载数据
onMounted(async () => {
  // 首次加载数据
  await getStudentInfoDataList()
})
</script>

<template>
  <view class="container" :style="{ paddingTop: safeAreaInsets!.top + 'px' }">
    <view class="page-header">
      <text class="page-title">学生点评</text>
    </view>

    <uni-forms ref="recordForm" :modelValue="formData" label-width="160rpx" class="form-container">
      <uni-forms-item label="学生" required>
        <uni-data-picker
          placeholder="请选择学生"
          popup-title="请选择班级/学生"
          :localdata="studentInfoList"
          v-model="formData.studentId"
          level="3"
          range-key="text"
          :clear-icon="false"
          @change="onPickerChange"
        >
        </uni-data-picker>
      </uni-forms-item>
      <uni-forms-item label="点评时间" required>
        <uni-datetime-picker
          type="datetime"
          v-model="formData.classTime"
          placeholder="选择点评时间"
        />
      </uni-forms-item>
      <uni-forms-item label="点评内容">
        <uni-easyinput
          type="textarea"
          v-model="formData.comment"
          placeholder="请输入点评内容"
          :maxlength="200"
        />
      </uni-forms-item>
      <uni-forms-item label="综合评分">
        <uni-rate v-model="formData.score" :max="5" :min="1" :star-size="36" color="#FF7D00" />
      </uni-forms-item>
      <uni-forms-item label="活跃度">
        <uni-rate
          v-model="formData.activityScore"
          :max="5"
          :min="1"
          :star-size="36"
          color="#FF7D00"
        />
      </uni-forms-item>
      <uni-forms-item label="参与度">
        <uni-rate
          v-model="formData.participationScore"
          :max="5"
          :min="1"
          :star-size="36"
          color="#FF7D00"
        />
      </uni-forms-item>
      <!-- 图片上传 -->
      <uni-forms-item label="上传图片">
        <uni-file-picker
          v-model="formData.images"
          file-mediatype="image"
          mode="grid"
          :limit="9"
          :sizeType="['compressed']"
          :max-size="5 * 1024 * 1024"
          title="点击上传"
          @select="onFileSelect"
          @delete="onFileDelete"
        ></uni-file-picker>
      </uni-forms-item>
    </uni-forms>

    <view class="button-group">
      <button type="default" @click="back">取消</button>
      <button type="primary" @click="submitRecord">提交</button>
    </view>
  </view>
</template>

<style lang="scss">
.container {
  padding: 20rpx;
  box-sizing: border-box;
  background-color: $archive-bg-color;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx 0;
  margin-bottom: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: $archive-text-main;
}

.form-container {
  margin-bottom: 40rpx;
  background-color: #fff;
  border-radius: $archive-card-radius;
  box-shadow: $archive-card-shadow;
  padding: 24rpx;
}

.button-group {
  display: flex;
  justify-content: space-between;
  gap: 20rpx;
  padding: 20rpx;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top: 1rpx solid #f0f0f0;
  box-sizing: border-box;
}

.button-group button {
  flex: 1;
  border-radius: 44rpx;
  height: 88rpx;
  line-height: 88rpx;
  font-size: 32rpx;
  margin: 0;
}

.button-group button[type='default'] {
  background-color: #f5f5f5;
  color: $archive-text-secondary;
}

.button-group button[type='primary'] {
  background-color: $archive-primary-color;
  color: #fff;
}

/* 评分组件样式 */
.uni-rate {
  margin-top: 8rpx;
}

/* 三级选择器选项样式 */
.data-pickerview__item {
  &:nth-child(1) {
    color: $archive-text-main;
    font-weight: bold;
  }
}

/* 文本框样式 */
.uni-easyinput__textarea {
  min-height: 200rpx !important;
  border: 1rpx solid #f0f0f0;
  border-radius: 8rpx;
  padding: 20rpx;
}

/* 文件选择器样式 */
.uni-file-picker {
  margin-top: 10rpx;
}

.uni-file-picker__list {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.uni-file-picker__list-item {
  width: 180rpx;
  height: 180rpx;
  border-radius: 8rpx;
  overflow: hidden;
}

.uni-file-picker__add {
  width: 180rpx;
  height: 180rpx;
  border: 2rpx dashed #e0e0e0;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
}
</style>
